package com.chanceit.ssss.button;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.gl.utils.Tip;
import org.gl.utils.lg;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;

import com.chanceit.ssss.activity.R;
import com.chanceit.ssss.data.DataSources;

public class CallPhoneListener extends PhoneStateListener implements
		OnClickListener {

	private boolean isPhoneCalling = false;
	private long callTime = 0l;

	String LOG_TAG = "CallPhoneListener";
	JSONObject useinfo;

	public CallPhoneListener(JSONObject selectCarerInfo) {
		this.useinfo = selectCarerInfo;
	}

	@Override
	public void onCallStateChanged(int state, String incomingNumber) {
		if (TelephonyManager.CALL_STATE_RINGING == state) {
			// phone ringing
			lg.i(LOG_TAG, "RINGING, number: " + incomingNumber);
		}

		if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
			// active
			lg.i(LOG_TAG, "OFFHOOK");

			isPhoneCalling = true;
			if (callTime <= 0) {
				callTime = System.currentTimeMillis();
				listenOutCallState();
			}
		}

		if (TelephonyManager.CALL_STATE_IDLE == state) {
			// run when class initial and phone call ended,
			// need detect flag from CALL_STATE_OFFHOOK
			lg.i(LOG_TAG, "IDLE");

			if (isPhoneCalling) {

				// lg.i(LOG_TAG, "restart app");

				// // restart app
				// Intent i = getBaseContext().getPackageManager()
				// .getLaunchIntentForPackage(
				// getBaseContext().getPackageName());
				// i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				// startActivity(i);
				if (useinfo != null) {
					lg.i(LOG_TAG, "拨打过" + useinfo.optString("tel"));
					long time = System.currentTimeMillis() - callTime;
					callTime = 0;
					DataSources ds = new DataSources();
					AjaxParams par = new AjaxParams();
					par.put("op", "saveLog");
					par.put("missed", isActive?"true":"false");
					par.put("called", "false");
					par.put("code", useinfo.optString("tel"));
					par.put("callTimeSpan", time / 1000 + "");
					par.put("timpano",""+System.currentTimeMillis());
					par.put("type",""+useinfo.optString("callType"));
					ds.getData("call_service", null, par,
							new AjaxCallBack<String>() {
								@Override
								public void onSuccess(String t) {
									super.onSuccess(t);
									lg.i(LOG_TAG, "" + t);
									try {
										JSONObject temp = new JSONObject(t);
										if (temp.optInt("code") != 0) {
											lg.e(LOG_TAG,
													"call_service save fial:"
															+ temp.optString("reason"));
										}
									} catch (Exception e) {
										e.printStackTrace();
										onFailure(e, 0, e.getMessage());
									}
								}

								@Override
								public void onFailure(Throwable t, int errorNo,
										String strMsg) {
									super.onFailure(t, errorNo, strMsg);
									lg.e(LOG_TAG, strMsg);
								}
							});
				}
				isPhoneCalling = false;
			}

		}
	}

	@Override
	public void onClick(View v) {
		String tel = null;
		if (useinfo != null) {
			tel = useinfo.optString("tel");
		}
		if (!TextUtils.isEmpty(tel)) {
			v.getContext();
			TelephonyManager telephonyManager = (TelephonyManager) v
					.getContext().getSystemService(Context.TELEPHONY_SERVICE);
			telephonyManager.listen(this, PhoneStateListener.LISTEN_CALL_STATE);
			Intent phoneIntent = new Intent("android.intent.action.CALL",
					Uri.parse("tel:" + tel));
			v.getContext().startActivity(phoneIntent);
		} else {
			Tip.show(v.getContext().getString(R.string.error_tel_requied));
		}

	}

	/**
	 * 是否接通
	 */
	boolean isActive = false;

	private void listenOutCallState() {
		Process process;
		InputStream inputstream;
		BufferedReader bufferedreader;
		long timeout = 300*60*1000;
		try {
			process = Runtime.getRuntime().exec("logcat -v time -b radio");
			inputstream = process.getInputStream();
			InputStreamReader inputstreamreader = new InputStreamReader(
					inputstream);
			bufferedreader = new BufferedReader(inputstreamreader);
			String str = "";
			long current = System.currentTimeMillis();
			while (isPhoneCalling&&timeout<(System.currentTimeMillis()-current)) {
				if ((str = bufferedreader.readLine()) != null) {
					lg.i(LOG_TAG, str);
					if (str.contains("GET_CURRENT_CALLS")
							&& str.contains("ACTIVE")) {
						isActive = true;
					}
				}
			}
			isActive = false;
		} catch (Exception e) {

		}
	}

}
